package com.tangye.massageshop.controller;

import com.alibaba.fastjson.JSON;
import com.tangye.massageshop.entity.UserEntity;
import com.tangye.massageshop.enums.RoleEnum;
import com.tangye.massageshop.exception.ShopException;
import com.tangye.massageshop.service.UserService;
import com.tangye.massageshop.util.JwtUtil;
import com.tangye.massageshop.util.MD5Utils;
import com.tangye.massageshop.util.Result;
import com.tangye.massageshop.util.ThreadLocalUtil;
import lombok.extern.log4j.Log4j2;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.validation.constraints.NotBlank;
import java.util.List;
import java.util.Objects;

@Log4j2
@RestController
@RequestMapping("/system")
public class SystemController {

    @Resource
    private UserService userService;

    @PostMapping("/addAdminUser")
    public Result<String> addAdminUser(){
        log.info(JSON.toJSONString(ThreadLocalUtil.get()));
        UserEntity userEntity = new UserEntity();
        userEntity.setUserName("admin");
        //user.setPassword("admin123");
        userEntity.setPassword(MD5Utils.encryptByMd5("admin123"));
        userEntity.setCompanyId(0);
        userEntity.setCompanyName("admin");
        userEntity.setRole(RoleEnum.ADMIN.getCode());
        userService.add(userEntity);
        return Result.ok();
    }

    @PostMapping("/login")
    public Result<String> login(String userName, String password){
        UserEntity userEntity = userService.loginCheck(userName, password);
        if (Objects.nonNull(userEntity)) {
            String token = JwtUtil.getToken(userEntity);
            return Result.success(token);
        }
        return Result.error("用户名或密码错误");
    }

    @GetMapping("/initPassword")
    public Result<String> initPassword(@RequestParam @NotBlank String userName) {
        UserEntity userEntity = ThreadLocalUtil.get();
        if (!userEntity.isAdmin()) {
            return Result.error("非超级管理员");
        }
        userService.initPassword(userName);
        return Result.ok();
    }

    @PostMapping("queryUserList")
    public Result<List<UserEntity>> queryUserList(UserEntity userEntity) {
        log.info("入参：{}",JSON.toJSONString(userEntity));
        UserEntity userSession = ThreadLocalUtil.get();
        if (!userSession.isAdmin()) {
            throw new ShopException("非超级管理员");
        }
        List<UserEntity> userEntities = userService.queryUserListPage(userEntity);
        return Result.success(userEntities);
    }

}
